home *** CD-ROM | disk | FTP | other *** search
- Path: cypher.3do.com!user
- From: tsw@3do.com (Tom Watson)
- Newsgroups: comp.lang.c
- Subject: Re: String Problem
- Date: Mon, 25 Mar 1996 17:21:13 -0800
- Organization: The 3DO Corporation
- Distribution: world
- Message-ID: <tsw-2503961721130001@cypher.3do.com>
- References: <4j6l61$4no@B1FF.mindspring.com>
- NNTP-Posting-Host: cypher.3do.com
-
- In article <4j6l61$4no@B1FF.mindspring.com>, vtipres@atl.mindspring.com wrote:
-
- > This is supposed to be a variation on sample code from a textbook.
- > Can anyone tell me why NameCheck = 0 when I run the program?
- >
- > /*
- > Testing character transactions.
- > */
- >
- > #include <stdio.h>
- > #include <ctype.h>
- >
- > int main()
- > {
- > char Name[11] = "John";
-
- You have initialized a local variable to the text "John" (with a trailing
- 'nul' character. After that (the first 5 locations in the array) the data
- is undefined.
-
- > char *WhereName;
- > int NameCheck = 0;
- >
- > WhereName = Name;
- >
- > if ( WhereName == "John" )
-
- Here you are comparing a character pointer with the address of a constant
- (could be in read-only storage). This is a completely different "John"
- from the first. In ANSI C this cannot be changed, whereas the first one
- (declared in the 'Name' array) can be altered to your hearts content.
-
- > {
- > NameCheck = 1;
- > }
- >
- > printf( "Name: %s\n", Name );
- > printf( "NameCheck = %i\n", NameCheck );
- > printf( "WhereName = %i\n", WhereName );
-
- The variable 'WhereName' is a pointer, and should not be printed with a
- '%i' formatting specification. Pointers can be different sizes than ints
- (I use a compiler that this is the case!). It should be printed with a
- '%p' specification if you want to see what it is.
-
-
- > }
-
-
- The basic problem is that your 'if' statement looks as if you want to
- compare the two strings ans see if they are equal. This cannot be done in
- the base language wiothout using the library. If you really want to
- compare the strings, the proper call might look like:
-
- if (strcmp (WhereName, "John") == 0)
-
- In any event, a good looking at the FAQ's might answer some of these
- things. Even if it doesn't, it contains quite a bit of VERY good clues on
- lots of topics.
-
- p.s. What textbook??
-
- --
- Tom Watson
- tsw@3do.com (Home: tsw@johana.com)
-